package shujia.day04.homework;

import com.sun.corba.se.impl.legacy.connection.USLPort;

/*
     合并数组操作：现有如下一个数组： int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}
     要求将以上数组中值为0的项去掉，将不为0的值存入一个新的数组，
     生成的新数组为： int newArr [] ={1,3,4,5,6,6,5,4,7,6,7,5}
 */
public class Test2 {
    public static void main(String[] args) {
        int[] oldArr = {1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5};
        System.out.println("旧数组：");
        printIntArray(oldArr);

        //统计不为0的元素个数
        int count = 0;
        for (int i = 0; i < oldArr.length; i++) {
            if (oldArr[i] != 0) {
                count++;
            }
        }

        //通过不为0的个数计算新数组的长度
        int[] newArr = new int[count];

        //遍历旧数组将不为0的元素放入新数组中
        for (int i = 0, j = 0; i < oldArr.length; i++) {
            if(oldArr[i]!=0){
                newArr[j++] = oldArr[i];
            }
        }

        System.out.println("新数组：");
        printIntArray(newArr);



    }

    public static void printIntArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            if (i == 0) {
                System.out.print("[" + array[i] + ",");
            } else if (i == array.length - 1) {
                System.out.println(array[i] + "]");
            } else {
                System.out.print(array[i] + ",");
            }
        }
    }
}
